import type { ConnectState } from '@/models/connect';
import { LoadingOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, Divider, message, Spin, Upload } from 'antd';
import React, { useState } from 'react';
import { connect } from 'umi';

const antIcon = <LoadingOutlined  style={{ fontSize: 16 }} spin />

const PermissionManage: React.FC<any> = ({
  perm,
  text,
  type,
  buttonSize,
  user,
  value,
  divider,
  onClick,
  onChange,
}) => {
  const {
    currentUser: { perms = [''] },
  } = user;

  const [postFileList, setPostFileList] = useState<any[]>(value || []);
  const [uploadloading, setUploadloading] = useState<boolean>(false);

  const judgePerms = () => {
    if (perms.indexOf(perm) > -1) {
      return true
    }else{
      return false
    }
  }

  const propPostChange = (pFs: any) => {
    if (onChange) {
      onChange(pFs);
    }
  };

  const handleUploadChange = ({ fileList: newFileList = [], file = {} }:any) => {
    //如果没有status，认为被beforeUpload拦截
    if (!file.status) {
      return;
    }
    setUploadloading(true)
    if (file.status == 'done') {
      const response = file.response;
      if (response && response.success) {
        setPostFileList((files) => {
          let list = [Object.assign({ ...file }, response.data, { type: [] })];
          propPostChange(list);
          return list;
        });
      } else {
        file.status = 'error';
        file.name = response.errMsg || '上传失败';
        message.error(response.errMsg || '系统超时，请刷新重试！');
      }
      setUploadloading(false)
    }
  }

  const props: UploadProps = {
    name: 'file',
    showUploadList:false,
    action: '/api/upload/resource',
    maxCount:1,
    data:{
      ossEnum:'MARGIN_ACCOUNT'
    },
    onChange:(file)=>{handleUploadChange(file)}
  };


  return (
      judgePerms() ? 
      (
        type == 'button' ? 
        <Button key="button" type="primary" size={buttonSize ? buttonSize : 'middle'} onClick={onClick}>
          {text}
        </Button>
        :
        type == 'upload' ? 
        <Spin  style={{display:'inline-block'}} indicator={antIcon} spinning={uploadloading}>
          <Upload  {...props}>
            <a style={{whiteSpace:'nowrap'}} onClick={onClick} >{text}</a>
          </Upload>
        </Spin>
        :
        <a style={{whiteSpace:'nowrap'}} onClick={onClick} >{text}{divider === false ? null : <Divider type="vertical" />}</a>
      )
      :''
  );
};

export default connect(({user}: ConnectState)=>({
  user
}))(PermissionManage)
;
